package youleche.com.controler.servlet;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import youleche.com.business.BSeller;
import youleche.com.business.BVehicleImageInfo;
import youleche.com.common.IDFactory;
import youleche.com.factory.MLLogFactory;
import youleche.com.model.MSeller;
import youleche.com.model.MVehicleImageInfo;
import youleche.com.sql.servlet.common.SuperHttpServlet;
import youleche.com.util.DateUtil;
import youleche.com.util.ImageFactory;

/**
 * 图片上传
 */
public class SImgUploadServlet extends SuperHttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SImgUploadServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) {
		int action = Integer.parseInt(request.getParameter("action"));
		switch(action){
			case 0: 
				//上传图片
				this.uploadImg(request, response);
				break;
			case 1:
				//删除图片
				this.deleteImg(request, response);
				break;
			case 2:
				//把图片复制到正式图片库中
				this.copyImg(request, response);
				break;
			case 3: 
				//上传用户认证图片
				this.uploadCertifyImg(request, response);
				break;
			case 4: 
				//删除用户认证图片
				this.deleteCertifyImg(request, response);
				break;
			case 5: 
				//上传租车信息图片
				this.uploadRentImg(request, response);
				break;
			case 6: 
				//复制图片到正式库（针对租车信息）
				this.copyImgForRentInfo(request, response);
				break;
		}
		
	}
	
	/**
	 * 上传租车信息图片
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("rawtypes")
	private void uploadRentImg(HttpServletRequest request, HttpServletResponse response){
		try {
			request.setCharacterEncoding("UTF-8");
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(1024 * 1024 * 10); //最多上传10M的图片(感觉10M太大了)
			ServletFileUpload upload = new ServletFileUpload(factory);
			List items = upload.parseRequest(request);
			Iterator it = items.iterator();
			while (it.hasNext()) {
				FileItem item = (FileItem) it.next();
				if (!item.isFormField()) {
					if(item.getSize() > 1024 * 1024 * 10 ){
						super.response_contentType_application_textplain(response, "上传图片的大小不能超过5M");
						return;
					}
					if (item.getName() != null && !item.getName().equals("")) {
						String fileName = item.getName();
						String extName = "";
						if(fileName.lastIndexOf(".") >= 0){
							extName = fileName.substring(fileName.lastIndexOf("."));
							String extNames =".jpg,.png,.jpeg,.gif,.JPG,.PNG,.JPEG,.GIF";
							if(!extNames.contains(extName)){
								super.response_contentType_application_textplain(response, "只能上传jpg,png,jpeg,gif格式的图片");
								break;
							}
							extName = fileName.substring(fileName.lastIndexOf("."));
							String imgId = IDFactory.getId("mlc", "vehicleImageInfo");
							this.writeImageToTempImage(item, extName, imgId, request, response);
							String tempDic = "/vehicleImageTemp/";
							if(!this.isLocalAddr(request)){
								tempDic = "/meileche" + tempDic;
							}
							
							super.response_contentType_application_textplain(response, tempDic + imgId +  extName +"^" + imgId + extName);
					        break;
						}else{
							continue;
						}
					}else{
						continue;
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
			super.response_contentType_application_textplain(response, "");
		} catch (Exception e) {
			e.printStackTrace();
			super.response_contentType_application_textplain(response, "");
		}
	}
	
	/**
	 * 删除用户认证图片
	 * @param request
	 * @param response
	 */
	private void deleteCertifyImg(HttpServletRequest request, HttpServletResponse response){
		String imgSrc = request.getParameter("id");
		String userId = request.getParameter("userId");
		try {
			
			ImageFactory.deleteCertifyImage(userId, imgSrc);
			BSeller handler = new BSeller();
			MSeller seller = new MSeller();
			seller.setUserId(userId);
			seller.setShopImgUrl("0");
			handler.updateSellerImageUrlById(seller);
		} catch (Exception e) {
			e.printStackTrace();
		}
			
	}
	
	/**
	 * 把图片复制到正式图片库中(针对租车信息)
	 * @param request
	 * @param response
	 */
	private void copyImgForRentInfo(HttpServletRequest request, HttpServletResponse response){
		String imgIds = request.getParameter("imgIds");
		String rentId = request.getParameter("rentId");
		try {
			String tempDir = this.getServletConfig().getServletContext().getRealPath("") + "/vehicleImageTemp/";
			String normalDir = this.getServletConfig().getServletContext().getRealPath("") + "/vehicleImage/";
			ImageFactory.handleImagesByBatch_rent(imgIds, tempDir, normalDir, rentId);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			MLLogFactory.exceptionLog("复制图片到正式库中", "发生异常", e.getMessage(), "localhost");
		}
			
	}
	
	/**
	 * 把图片复制到正式图片库中
	 * @param request
	 * @param response
	 */
	private void copyImg(HttpServletRequest request, HttpServletResponse response){
		String imgIds = request.getParameter("imgIds");
		String vehicleId = request.getParameter("vehicleId");
		try {
			String tempDir = this.getServletConfig().getServletContext().getRealPath("") + "/vehicleImageTemp/";
			String normalDir = this.getServletConfig().getServletContext().getRealPath("") + "/vehicleImage/";
			ImageFactory.handleImagesByBatch(imgIds, tempDir, normalDir, vehicleId);
		} catch (Exception e) {
			MLLogFactory.exceptionLog("复制图片到正式库中", "发生异常", e.getMessage(), "localhost");
		}
			
	}
	
	/**
	 * 上传用户认证图片
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("rawtypes")
	private void uploadCertifyImg(HttpServletRequest request, HttpServletResponse response){
		try {
			request.setCharacterEncoding("UTF-8");
			String userId = request.getParameter("id");
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List items = upload.parseRequest(request);
			Iterator it = items.iterator();
			while (it.hasNext()) {
				FileItem item = (FileItem) it.next();
				if (!item.isFormField()) {
					if (item.getName() != null && !item.getName().equals("")) {
						String fileName = item.getName();
						String extName = "";
						if(fileName.lastIndexOf(".") >= 0){
							extName = fileName.substring(fileName.lastIndexOf("."));
							this.write300_80Image(userId, item, extName, request, response);
							super.response_contentType_application_textplain(response, "/meileche/userImage/"+ userId +"-300_80"+  extName);
					        break;
						}else{
							continue;
						}
					}else{
						continue;
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
			super.response(response, "");
		} catch (Exception e) {
			e.printStackTrace();
			super.response(response, "");
		}
	}
	
	/**
	 * 删除图片
	 * @param request
	 * @param response
	 */
	private void deleteImg(HttpServletRequest request, HttpServletResponse response){
		String imgId = request.getParameter("imgId");
		try {
			ImageFactory.deleteRelativeImagesByBatch(imgId, this.getServletConfig().getServletContext().getRealPath("") + "/vehicleImageTemp/");
		} catch (Exception e) {
			e.printStackTrace();
		}
			
	}
	
	/**
	 * 上传
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("rawtypes")
	private void uploadImg(HttpServletRequest request, HttpServletResponse response){
		try {
			request.setCharacterEncoding("UTF-8");
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(1024 * 1024 * 10); //最多上传10M的图片
			ServletFileUpload upload = new ServletFileUpload(factory);
			List items = upload.parseRequest(request);
			Iterator it = items.iterator();
			while (it.hasNext()) {
				FileItem item = (FileItem) it.next();
				if (!item.isFormField()) {
					if(item.getSize() > 1024 * 1024 * 10 ){
						super.response_contentType_application_textplain(response, "上传图片的大小不能超过5M");
						return;
					}
					if (item.getName() != null && !item.getName().equals("")) {
						String fileName = item.getName();
						String extName = "";
						if(fileName.lastIndexOf(".") >= 0){
							extName = fileName.substring(fileName.lastIndexOf("."));
							String extNames =".jpg,.png,.jpeg,.gif,.JPG,.PNG,.JPEG,.GIF";
							if(!extNames.contains(extName)){
								super.response_contentType_application_textplain(response, "只能上传jpg,png,jpeg,gif格式的图片");
								break;
							}
							
							String imgId = this.write100_100Image(item, extName, request, response);
							this.writeNormalImage(item, extName, imgId, request, response);
							this.write200_200Image(item, extName,imgId, request, response);
							this.write300_300Image(item, extName, imgId, request, response);
							String tempDic = "/vehicleImageTemp/";
							if(!this.isLocalAddr(request)){
								tempDic = "/meileche" + tempDic;
							}
							
							super.response_contentType_application_textplain(response, tempDic + imgId +"-100_100"+  extName +"^" + imgId + extName);
					        break;
						}else{
							continue;
						}
					}else{
						continue;
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
			super.response_contentType_application_textplain(response, "");
		} catch (Exception e) {
			e.printStackTrace();
			super.response_contentType_application_textplain(response, "");
		}
	}
	
	/**
	 * 判断是否是本地地址
	 * @param request 请求对象
	 * @return 返回bool值 true 不是
	 */
	private boolean isLocalAddr(HttpServletRequest request){
		StringBuffer url = request.getRequestURL();
		if(url.toString().contains("http://www.meileche.com")){
			return true;
		}else if(url.toString().contains("http://localhost:8080")){
			return false;
		}else{
			return false;
		}
	}
	
	/**
	 * 写正常的图片
	 * @param item 文件项
	 * @param extName 文件后缀名
	 * @param preId ID前缀名
	 */
	private void writeNormalImage(FileItem item, String extName, String preId, HttpServletRequest request,HttpServletResponse response){

		MLLogFactory.accLog("用户上传车辆报价信息正常图片", "用户上传车辆报价信息正常图片", "上传正常大小图片", request.getRemoteAddr());
		String newFileName = preId +  "-normal" + extName;
		String filePath = this.getServletConfig().getServletContext().getRealPath("") + "/vehicleImageTemp/" + newFileName;
		File file = new File(filePath);
		try {
			item.write(file);
		} catch (Exception e) {
			MLLogFactory.exceptionLog("用户上传车辆报价信息正常图片发生异常", "用户上传车辆报价信息正常图片发生异常", e.getMessage(), request.getRemoteAddr());
		}
		
        String infoPath = "/meileche/vehicleImageTemp/" + newFileName;        
		//this.addVehicleImageInfo(infoPath,"0", request, response);
	}
	
	
	/**
	 * 写正常的图片到临时库
	 * @param item 文件项
	 * @param extName 文件后缀名
	 * @param preId ID前缀名
	 */
	private void writeImageToTempImage(FileItem item, String extName, String preId, HttpServletRequest request,HttpServletResponse response){

		String newFileName = preId  + extName;
		String filePath = this.getServletConfig().getServletContext().getRealPath("") + "/vehicleImageTemp/" + newFileName;
		File file = new File(filePath);
		try {
			item.write(file);
		} catch (Exception e) {
			MLLogFactory.exceptionLog("用户上传车辆报价信息正常图片发生异常", "用户上传车辆报价信息正常图片发生异常", e.getMessage(), request.getRemoteAddr());
		}
	}
	
	/**
	 * 存200*200大小的图片
	 * @param item 文件项
	 * @param extName 文件后缀名
	 * @param preId ID前缀名
	 */
	private void write200_200Image(FileItem item, String extName, String preId, HttpServletRequest request,HttpServletResponse response){
		String newFileName = preId +"-200_200"+  extName;
		String filePath = request.getSession().getServletContext().getRealPath("/") + "vehicleImageTemp/" + newFileName;
		System.out.println(filePath);
		Image bufImg;
		try {
			bufImg = ImageIO.read(item.getInputStream());
			int width = 200;
			int height = 200;
	        BufferedImage bf = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
	        bf.getGraphics().drawImage(bufImg,0,0,width,height,null);
	        FileOutputStream newimage=new FileOutputStream(filePath);
	        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
	        encoder.encode(bf);
	        newimage.close();
	        String infoPath = "/meileche/vehicleImageTemp/" + newFileName;
			//this.addVehicleImageInfo(infoPath, "1", request, response);
		} catch (IOException e) {
			MLLogFactory.exceptionLog("用户上传车辆报价信息200-200图片发生异常", "用户上传车辆报价信息200-200图片发生异常", e.getMessage(), request.getRemoteAddr());
			super.response(response, "");
		}
		
	}
	
	/**
	 * 存100_100大小的图片
	 * @param item 文件项
	 * @param extName 文件后缀名
	 */
	private String write100_100Image(FileItem item, String extName, HttpServletRequest request,HttpServletResponse response){
		MLLogFactory.accLog("用户上传车辆报价信息100-100图片", "用户上传车辆报价信息100-100图片", "上传100-100大小图片", request.getRemoteAddr());
		
		String imgId = IDFactory.getId("meileche", "vehicleImageInfo");
		String newFileName = imgId +"-100_100"+  extName;
		String filePath = this.getServletConfig().getServletContext().getRealPath("") + "/vehicleImageTemp/" + newFileName;
	
		Image bufImg;
		try {
			bufImg = ImageIO.read(item.getInputStream());
			int width = 100;
			int height = 100;
	        BufferedImage bf = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
	        bf.getGraphics().drawImage(bufImg,0,0,width,height,null);
	        FileOutputStream newimage=new FileOutputStream(filePath);
	        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
	        encoder.encode(bf);
	        newimage.close();
			//this.addVehicleImageInfo(infoPath, "1", request, response);
		} catch (IOException e) {
			MLLogFactory.exceptionLog("用户上传车辆报价信息100-100图片发生异常", "用户上传车辆报价信息100-100图片发生异常",e.getMessage(), request.getRemoteAddr());
			super.response(response, "");
		}
		
		return imgId;
	}
	
	/**
	 * 存300_80大小的图片
	 * @param item 文件项
	 * @param extName 文件后缀名
	 */
	private String write300_80Image(String userId, FileItem item, String extName, HttpServletRequest request,HttpServletResponse response){
		MLLogFactory.accLog("用户上传车辆报价信息300_80图片", "用户上传车辆报价信息300_80图片", "上传300_80大小图片", request.getRemoteAddr());
		
		String newFileName = userId +"-300_80"+  extName;
		String filePath = this.getServletConfig().getServletContext().getRealPath("") + "/userImage/" + newFileName;
	
		Image bufImg;
		try {
			bufImg = ImageIO.read(item.getInputStream());
			int width = 300;
			int height = 80;
	        BufferedImage bf = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
	        bf.getGraphics().drawImage(bufImg,0,0,width,height,null);
	        FileOutputStream newimage=new FileOutputStream(filePath);
	        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
	        encoder.encode(bf);
	        newimage.close();
	        BSeller handler = new BSeller();
			MSeller seller = new MSeller();
			seller.setUserId(userId);
			seller.setShopImgUrl(newFileName);
			handler.updateSellerImageUrlById(seller);
	        this.asynAdd(newFileName, "4", userId);
		} catch (Exception e) {
			MLLogFactory.exceptionLog("用户上传车辆报价信息300_80图片发生异常", "用户上传车辆报价信息300_80图片发生异常", e.getMessage(), request.getRemoteAddr());
			
			return "";
		}
		
		return newFileName;
	}
	
	/**
	 * 存300_300大小的图片
	 * @param item 文件项
	 * @param extName 文件后缀名
	 * @param preId 100_100返回的Id
	 */
	private void write300_300Image(FileItem item, String extName, String preId, HttpServletRequest request,HttpServletResponse response){
		MLLogFactory.accLog("用户上传车辆报价信息300-300图片", "用户上传车辆报价信息300-300图片","用户上传车辆报价信息300-300图片", request.getRemoteAddr());
		
		String newFileName = preId +"-300_300"+  extName;
		String fileDic = request.getSession().getServletContext().getRealPath("/") + "vehicleImageTemp/";
		File file = new File(fileDic);
		if(!file .exists()  && !file .isDirectory()){  
		    file .mkdir();    
		} else{
		}
		String filePath = fileDic + newFileName;
		MLLogFactory.accLog("用户上传车辆报价信息300-300图片文件路径", "用户上传车辆报价信息300-300图片文件路径",filePath, request.getRemoteAddr());
		
		Image bufImg;
		try {			
			bufImg = ImageIO.read(item.getInputStream());
			int width = 300;
			int height = 300;
	        BufferedImage bf = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
	        bf.getGraphics().drawImage(bufImg,0,0,width,height,null);
	        FileOutputStream newimage=new FileOutputStream(filePath);
	        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
	        encoder.encode(bf);
	        newimage.close();
	        String infoPath = "/meileche/vehicleImageTemp/" + newFileName;
			//this.addVehicleImageInfo(infoPath, "1", request, response);
		} catch (IOException e) {
			MLLogFactory.exceptionLog("用户上传车辆报价信息300-300图片发生异常", "用户上传车辆报价信息300-300图片发生异常", e.getMessage(), request.getRemoteAddr());
		
			super.response(response, "");
		}
		
	}
	
	/**
	 * 添加图片信息
	 * @param filePath 文件路径
	 */
	private void addVehicleImageInfo(String filePath,String type, HttpServletRequest request, HttpServletResponse response){
		
		this.asynAdd(filePath, type, request.getParameter("vehicleId"));
	}
	
	private void asynAdd(String filePath, String type, String vehicleId){
		MVehicleImageInfo image = new MVehicleImageInfo();
		image.setAddTime(DateUtil.getNowDate());
		image.setImageId(IDFactory.getId("meileche", "vehicleImageInfo"));
		image.setImagePath(filePath);
		image.setImageType(type);
		image.setSellerId("meileche");
		image.setVehicleId(vehicleId);
		try {			
			BVehicleImageInfo handler = new BVehicleImageInfo();
			handler.addVehicleImageInfo(image);
		} catch (Exception e) {
		}
	}
}
